<script setup lang="ts">
  import { ref, defineEmits, computed, watch, onMounted, nextTick } from 'vue';
  import { useBooleanStore } from '@/store';
  import {
    scanningHandover,
    searchWorkerCode,
    changeAccType,
  } from '@/api/material-receipt';
  import { Notification } from '@arco-design/web-vue';

  const emit = defineEmits(['updateArray']);
  const booleanStore = useBooleanStore();
  const hStyle = ref({
    'background-color': booleanStore.color,
    'border-radius': booleanStore.borderRadius,
  });
  const scanInput = ref<any>('');
  const personCode = ref<string>('');
  // 表单查询数据
  const barcode = ref<string>('');
  const tuhao = ref<string>('');
  const qualityNumber = ref<string>('');
  const person = ref<string>('');
  const disabled = ref<boolean>(false);
  const loading = ref<boolean>(false);
  // 获取今天的日期
  const today = new Date();
  // 获取明天的日期
  const tomorrow = new Date();
  tomorrow.setDate(tomorrow.getDate() + 1);
  const startTime = ref<string>(today.toISOString().split('T')[0]);
  const endTime = ref<string>(tomorrow.toISOString().split('T')[0]);
  const pageSize = ref<number>(30);
  const pageNumber = ref<number>(1);
  const current = ref<number>(1);
  // const description = ref<string>('待完成');
  // const description2 = ref<string>('待完成');
  const scanCode = ref<string>('');

  // 发送搜索数据
  const flowQueryData = ref({
    searchParams: computed(() => ({
      barcode: barcode.value,
      itemCode: tuhao.value,
      qualityCode: qualityNumber.value,
      receiveEmpCode: person.value,
    })),
    pageParameter: computed(() => ({
      rows: pageSize.value,
      page: pageNumber.value,
    })),
    startTime: computed(() => startTime.value),
    endTime: computed(() => endTime.value),
    funcType: 'handOver',
  });
  // 表格数据
  async function handleSearch() {
    const newData = await scanningHandover(flowQueryData.value);
    emit('updateArray', newData);
  }

  // 重置
  function reset() {
    barcode.value = '';
    tuhao.value = '';
    qualityNumber.value = '';
    person.value = '';
    const [startDate] = today.toISOString().split('T');
    const [endDate] = tomorrow.toISOString().split('T');
    startTime.value = startDate;
    endTime.value = endDate;
    handleSearch();
  }

  // 扫码功能
  async function submit() {
    try {
      if (scanCode.value === '') {
        Notification.error({
          title: '失败',
          content: '请输入对应格式的条码',
          closable: true,
        });
        return;
      }
      if (personCode.value === '') {
        // 判断是否扫描员工号
        const info = ref({
          smPerson: computed(() => scanCode.value),
        });
        loading.value = true;
        const data = await searchWorkerCode(info.value);
        if (data.retCode === '200') {
          Notification.success({
            title: '成功',
            content: data.message,
            closable: true,
          });
          personCode.value = scanCode.value;
        } else {
          Notification.error({
            title: '失败',
            content: data.message ? data.message : '移交失败',
            closable: true,
          });
        }
        // 判断第二次扫描的是否还是员工号
      } else if (scanCode.value.length === 6) {
        const info = ref({
          smPerson: computed(() => scanCode.value),
        });
        loading.value = true;
        const data = await searchWorkerCode(info.value);
        if (data.retCode === '200') {
          Notification.success({
            title: '成功',
            content: data.message,
            closable: true,
          });
          personCode.value = scanCode.value;
        } else {
          Notification.error({
            title: '失败',
            content: data.message ? data.message : '移交失败',
            closable: true,
          });
        }
      } else {
        // 不是员工号后判断是那种物料
        // const scanBarcode = ref('');
        // const barcodeType = ref('');
        // const bzjCodeType = ref('');
        // if (scanCode.value.includes('{')) {
        //   const scanCodeObj: any = JSON.parse(scanCode.value);
        //   if ('CPHGZ' in scanCodeObj) {
        //     // 成品
        //     scanBarcode.value = scanCodeObj.CPHGZ;
        //     barcodeType.value = 'CP';
        //   } else {
        //     // 标件
        //     scanBarcode.value = scanCodeObj.CKCODE;
        //     barcodeType.value = 'BJ';
        //     bzjCodeType.value = scanCodeObj.BARCODETYPE; // BZJCK  BZJCKAO
        //   }
        // } else {
        //   // 85的零件不是纯数字 GW-222222
        //   scanBarcode.value = scanCode.value;
        //   barcodeType.value = 'LJ';
        // }
        // 调用接口，更改物料状态
        const receiveAndRjectcive = ref({
          barcode: scanCode.value,
          barcodeType: '',
          bzjCodeType: '',
          funcType: 'transfer',
          userCode: personCode.value,
        });
        disabled.value = true;
        loading.value = true;
        const data = await changeAccType(receiveAndRjectcive.value);
        if (data.retCode === '200') {
          Notification.success({
            title: '成功',
            content: data.message,
            closable: true,
          });
          // 更新数据
          handleSearch();
        } else {
          Notification.error({
            title: '失败',
            content: data.message ? data.message : '移交失败',
            closable: true,
          });
        }
      }
    } catch {
      Notification.error({
        title: '错误',
        content: '请确认输入法是否为英文输入或是否为正确的物料条码',
      });
    } finally {
      loading.value = false;
      disabled.value = false;
      scanCode.value = '';
      nextTick(() => {
        scanInput.value.focus();
      });
    }
  }

  function resetCode() {
    personCode.value = '';
  }
  onMounted(() => {
    nextTick(() => {
      scanInput.value.focus();
    });
    handleSearch();
  });
  // 监听分页
  watch([() => booleanStore.pageNum, () => booleanStore.pageSize], () => {
    if (booleanStore.num5 === 1) {
      pageNumber.value = booleanStore.pageNum;
      pageSize.value = booleanStore.pageSize;
      handleSearch();
    }
  });

  // 监听步骤条
  watch(personCode, () => {
    if (personCode.value === '') {
      current.value = 1;
    } else {
      current.value = 2;
    }
  });
</script>

<template>
  <!-- <a-card :header-style="hStyle">
    <template #title>
      <div class="font">流程进度</div>
    </template>
    <a-steps type="arrow" small changeable :current="current">
      <a-step :description="description">扫描工号</a-step>
      <a-step :description="description2">扫描条码</a-step>
    </a-steps>
  </a-card> -->
  <a-card :header-style="hStyle" :bordered="false">
    <template #title>
      <div class="font">扫码操作</div>
    </template>
    <a-row :gutter="{ md: 8, lg: 24, xl: 32 }">
      <a-col :span="6">
        <a-input-search
          ref="scanInput"
          v-model="scanCode"
          placeholder="请输入缓存箱/托盘码/条码"
          size="large"
          :disabled="disabled"
          :loading="loading"
          @keyup.enter="submit"
        />
      </a-col>
      <a-col :span="6">
        <a-button type="primary" size="large" @click="submit"
          >扫码移交</a-button
        >
        <a-button class="btn-reset" size="large" @click="resetCode"
          >重置</a-button
        >
      </a-col>
      <a-col :span="6">
        <div class="div-flex">
          <span>扫码人工号：</span>
          <span style="font-weight: bold; font-size: 18px">{{
            personCode
          }}</span>
        </div>
      </a-col>
    </a-row>
  </a-card>
  <a-card :header-style="hStyle" :bordered="false">
    <template #title>
      <div class="font">查询条件</div>
    </template>
    <a-row :gutter="{ md: 8, lg: 24, xl: 32 }">
      <a-col :span="6">
        <div>
          <a-input v-model="barcode" placeholder="条码" size="large" />
        </div>
      </a-col>
      <a-col :span="6">
        <div>
          <a-input v-model="tuhao" placeholder="零件图号" size="large" />
        </div>
      </a-col>
      <a-col :span="6">
        <div>
          <a-input
            v-model="qualityNumber"
            placeholder="质量编号"
            size="large"
          />
        </div>
      </a-col>
      <a-col :span="6">
        <div>
          <a-input v-model="person" placeholder="移交人工号" size="large" />
        </div>
      </a-col>
    </a-row>
    <a-row class="margin-top" :gutter="{ md: 8, lg: 24, xl: 32 }">
      <a-col :span="6">
        <div>
          <a-date-picker
            v-model="startTime"
            style="width: 100%"
            placeholder="移交时间"
            size="large"
          />
        </div>
      </a-col>
      <a-col :span="6">
        <div>
          <a-date-picker
            v-model="endTime"
            style="width: 100%"
            placeholder="到"
            size="large"
          />
        </div>
      </a-col>
      <a-col :span="6">
        <a-button type="primary" size="large" @click="handleSearch"
          >查询</a-button
        >
        <a-button class="btn-reset" size="large" @click="reset"
          >重置搜索框</a-button
        >
      </a-col>
    </a-row>
  </a-card>
</template>

<style scoped>
  .div-flex {
    display: flex;
    justify-content: center;
    align-items: center;
    white-space: nowrap;
  }
  .margin-top {
    margin-top: 10px;
  }
  .btn-group {
    float: right;
    margin-top: 15px;
  }

  .btn-reset {
    margin-left: 10px;
  }
  .font {
    font-size: 20px;
    color: black;
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI',
      Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue',
      sans-serif;
  }
</style>
